package com.tulele.vtool.task.async;

import com.alibaba.fastjson.JSONObject;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.model.thirdparty.WxPushUserInfo;
import com.tulele.vtool.bus.service.IUserService;
import com.tulele.vtool.bus.service.SysGzhService;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.util.DateUtil;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SysConstant;
import com.tulele.vtool.util.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class KefuMsgExpiredRemindAsyncTask {

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    //20200512 调整参数，多线程跑
    //@Async("taskExecutor")
    public void execute(String redisKey,String profile) throws Exception {

//        log.info("[enter KefuMsgExpiredRemindAsyncTask] = " + redisKey);

        Object pushUserJsonObject = redisCacheUtil.getCacheObject(redisKey);
        if (pushUserJsonObject != null) {

            String pushUserJson = (String)pushUserJsonObject;
            log.info("[pushUserJson] = " + pushUserJson);

            WxPushUserInfo wxPushUserInfo = JSONObject.parseObject(pushUserJson, WxPushUserInfo.class);

            String cacheTime = wxPushUserInfo.getCacheTime();
            if (StringUtils.isBlank(cacheTime)) {
                return;
            }

            int hours = DateUtil.getTimeDiff(3, cacheTime);

            DateTime spcialTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(cacheTime);
            spcialTime.plusHours(48);
            SimpleDateFormat f = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
            PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);

            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
            if(weixinService==null) {
                weixinService = objectFactory.getObject();
                weixinService.reSetConfigStorage(profile);
                WeixinServiceMap.putWeixinService(profile,weixinService);
            }

            UserInfo userInfo=userService.queryUserInfo(wxPushUserInfo.getUserId());
            if (hours >= 24 && hours <= 26) {


                String kefuMsg = "‼"+ userInfo.getNickName()+",这条消息很重要：\n" +
                        "\n" +
                        "\uD83D\uDC94当您收到这条消息，您已经超过 24 小时没有搭理我了！\n" +
                        "\n"+
                        "由于微信平台对小编的限制，如果要继续接收消息，\uD83D\uDE1C请帮小编一把：\n"+
                        "\n" +
                        "\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=唤醒小编&msgmenuid=+++\">回复【 9 】继续接收文章</a>\n"+
                        "\n" +
                        "\uD83D\uDE28为什么要点确认才能接收呢？\n"+
                        "\n" +
                        "\uD83D\uDC49<a href=\"weixin://bizmsgmenu?msgmenucontent=查看原因&msgmenuid=+++\">回复【 10 】查看原因</a>\n"+
                        "\n" +
                        "⚠提示：在下方对话框输入数字即可哦~ 不明白的<a href=\"weixin://bizmsgmenu?msgmenucontent=客服&msgmenuid=+++\">回复【 6 】加客服咨询！</a>";

                if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                    kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                }
                WxMpKefuMessage message=WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
                try {
                    weixinService.getKefuService().sendKefuMessage(message);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }

            }else if (hours > 45) {

                WxMpTemplateMessage templateMessage =WxMpTemplateMessage.builder()
                        // 接收者openid
                        .toUser(wxPushUserInfo.getOpenId())
                        // 模板id
                        .templateId(sysGzh.getSysGzh().getBusinessActivationTempId())//业务激活通知
                        // 模板跳转链接
                        .url(sysGzh.getCustomerMenuUrl())
                        .build();

                String firstMsg = "‼"+ userInfo.getNickName()+",这条消息很重要：\n" +
                        "\n" +
                        "\uD83D\uDC94当您收到这条消息，您已经超过45小时没有与我互动了！\n" +
                        "\n"+
                        "由于微信的改版，如果要继续给您发文章、您需要给我回复消息才可以激活！";

                String remarkMsg = "\uD83D\uDC49意向客户 回复 【 1 】\n"+
                        /*"\n" +
                        "\uD83D\uDC49人脉广场 回复 【 2 】\n"+*/
                        "\n" +
                        "\uD83D\uDC49最新爆文 回复 【 9 】\n"+
                        "\n" +
                        "⚠查看原因 回复【 10 】";

                // 添加模板数据
                templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                        .addData(new WxMpTemplateData("keyword1", "激活小编", "#ff0000"))
                        .addData(new WxMpTemplateData("keyword2", "点击左下角键盘，回复以下数字就可以了！", "#ff0000"))
                        .addData(new WxMpTemplateData("remark", remarkMsg, "#ff0000"));

                try {
                    weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
